const regeneratorRuntime = require('runtime.js');
const config = require('config.js');

const db = wx.cloud.database({
  env: config.env
})
const _ = db.command

/**
 * 获取评论列表
 */
function getCommentsList(page, flag) {
  return db.collection('mini_comments')
    .where({
      flag: flag
    })
    .orderBy('timestamp', 'desc')
    .skip((page - 1) * 10)
    .limit(10)
    .get()
}
/**
 * 根据id获取文章明细
 * @param {*} page 
 */
function getPostsById(id) {
  return db.collection('mini_posts')
    .doc(id)
    .get()
}
/**
 * 获取消息列表
 * @param {*} page 
 */
function getNoticeLogsList(page, openId) {
  return db.collection('mini_releases')
    .orderBy('timestamp', 'desc')
    .skip((page - 1) * 10)
    .limit(10)
    .get()
}

/**
 * 获取版本发布日志
 * @param {*} page 
 */
function getReleaseLogsList(page) {
  console.info('release page -> ', page)
  return db.collection('mini_releases')
    .where({
        key: 'releaseLogKey'
    })
    .orderBy('timestamp', 'desc')
    .skip((page - 1) * 10)
    .limit(10)
    .get();
}

async function getDocById(docTable, id) {
  console.info('get ' + docTable + ' id -> ' + id)
  let result = await wx.cloud.callFunction({
    name: 'adminService',
    data: {
      action: 'getDocById',
      docTable: docTable,
      id: id
    }
  })
  console.info('get ' + docTable + ' result -> ', result)
  return result
}

async function deleteDocById(docTable, id) {
  console.info('delete ' + docTable + ' id -> ' + id)
  let result = await wx.cloud.callFunction({
    name: 'adminService',
    data: {
      action: 'deleteDocById',
      docTable: docTable,
      id: id
    }
  })
  console.info('delete ' + docTable + ' result -> ', result)
  return true
}

async function saveAdminDoc(docTable, docData) {
  console.log('save ' + docTable + ' => ', docData)
  let result = await wx.cloud.callFunction({
    name: 'adminService',
    data: {
      action: 'saveDoc',
      docTable: docTable,
      docData: docData
    }
  })
  console.log('save ' + docTable + ' result => ', result)
  return true
}

async function getMajorList(page, filter, limit) {
  if (limit === undefined) {
    limit = 10
  }
  let where = {}
  if (filter.name !== undefined) {
    where.name = db.RegExp({
      regexp: filter.name,
      options: 'i'
    })
  } 
  return await db.collection('mini_majors').where(where)
    .orderBy('updateTime', 'desc')
    .skip((page - 1) * limit)
    .limit(limit)
    .get()
}

async function getCollegeList(page, filter, limit) {
  if (limit === undefined) {
    limit = 10
  }
  let where = {}
  if (filter.name != undefined) {
    where.name = db.RegExp({
      regexp: filter.name,
      options: 'i'
    })
  } 
  return await db.collection('mini_colleges').where(where)
    .orderBy('updateTime', 'desc')
    .skip((page - 1) * limit)
    .limit(limit)
    .get()
}

async function getGradeList(page, filter, limit) {
  if (limit === undefined) {
    limit = 10
  }
  let where = {}
  if (filter.name != undefined) {
    where.name = db.RegExp({
      regexp: filter.name,
      options: 'i'
    })
  } 
  return await db.collection('mini_grades').where(where)
    // .orderBy('name', 'asc')
    .skip((page - 1) * limit)
    .limit(limit)
    .get()
}

function getAuthorsList(page, filter, callback) {
  let where = {}
  if (filter.name != undefined) {
    where.name = db.RegExp({
      regexp: filter.name,
      options: 'i'
    })
  } else if (filter.nickname != undefined) {
    where.nickname = db.RegExp({
      regexp: filter.nickname,
      options: 'i'
    })
  } else if (filter._id != undefined) {
    where._id = db.RegExp({
      regexp: filter._id,
      options: 'i'
    })
  }
  if (filter.role != undefined) {
    where.role = filter.role
  }

  console.info('condition -> ', where)
  db.collection('mini_authors').where(where)
    .orderBy('createTime', 'desc')
    .skip((page - 1) * 10)
    .limit(10)
    .get()
    .then(callback)
    .catch(error => {
      console.error(error)
    })
}

async function getGradeById(id) {
  return await db.collection('mini_grades')
  .doc(id)
  .get()
}

function getAuthorById(id, callback) {
  return db.collection('mini_authors')
    .doc(id)
    .get()
    .then(callback)
    .catch(error => {
      console.error(error)
    })
}

function addPostDownload(postId) {
  return wx.cloud.callFunction({
    name: 'postsService',
    data: {
      action: "addPostDownload",
      postId: postId
    }
  })
}

function addPostView(data) {
  return wx.cloud.callFunction({
    name: 'postsService',
    data: {
      action: "addPostView",
      postId: data.postId
    }
  })
}

function getNewPostsList(page, filter, orderBy) {
  let where = {}
  if (filter.title != undefined) {
    where.title = db.RegExp({
      regexp: filter.title,
      options: 'i',
    })
  }
  if (filter.isShow != undefined) {
    where.isShow = filter.isShow
  }
  if (filter.classify != undefined) {
    where.classify = filter.classify
  }

  if (filter.hasClassify == 1) {
    where.classify = _.nin(["", 0, undefined])
  }

  if (filter.hasClassify == 2) {
    where.classify = _.in(["", 0, undefined])
  }

  if (orderBy == undefined || orderBy == "") {
    orderBy = "createTime"
  }

  if (filter.hasTag == 1) {
    where.tags = _.neq([])
  }

  if (filter.hasTag == 2) {
    where.tags = _.eq([])
  }

  if (filter.college !== undefined) {
    where.college = {}
    if (filter.college.name !== undefined
      && filter.college.name != '') {
        where.college.name = _.eq(filter.college.name)
    }
    if (filter.college.grade !== undefined
      && filter.college.grade != '') {
      where.college.grade = _.eq(filter.college.grade)
    }
    if (filter.college.major !== undefined
      && filter.college.major != '') {
      where.college.major = _.eq(filter.college.major)
    }
  }

  //不包含某个标签
  if (filter.containTag == 2) {
    where.tags = _.nin([filter.tag])
  }

  //包含某个标签
  if (filter.containTag == 1) {
    where.label = db.RegExp({
      regexp: filter.tag,
      options: 'i',
    })
  }

  //不包含某个主题
  if (filter.containClassify == 2) {
    where.classify = _.neq(filter.classify)
  }

  //包含某个主题
  if (filter.containClassify == 1) {
    where.classify = _.eq(filter.classify)
  }


  return db.collection('mini_posts')
    .where(where)
    .orderBy(orderBy, 'desc')
    .skip((page - 1) * 10)
    .limit(10)
    .field({
      _id: true,
      author: true,
      createTime: true,
      college: true,
      image: true,
      title: true,
      comments: true,
      downloads: true,
      views: true,
      favors: true,
      likes: true,
      isShow: true,
      classify: true,
      tags: true,
      digest: true
    }).get()
}
/**
 * 获取文章列表
 * @param {} page 
 */
function getPostsList(page, filter, isShow, orderBy, label) {
  let where = {}
  if (filter !== '') {
    where.title = db.RegExp({
      regexp: filter,
      options: 'i',
    })
  }
  if (isShow !== -1) {
    where.isShow = isShow
  }

  if (orderBy == undefined || orderBy == "") {
    orderBy = "createTime"
  }

  if (label != undefined && label != "") {
    where.label = db.RegExp({
      regexp: label,
      options: 'i',
    })
  }

  return db.collection('mini_posts')
    .where(where)
    .orderBy(orderBy, 'desc')
    .skip((page - 1) * 10)
    .limit(10)
    .field({
      _id: true,
      author: true,
      createTime: true,
      defaultImageUrl: true,
      title: true,
      totalComments: true,
      totalVisits: true,
      totalZans: true,
      isShow: true,
      classify: true,
      label: true,
      digest: true
    }).get()

}

/**
 * 获取评论列表
 * @param {} page 
 * @param {*} postId 
 */
function getPostComments(page, postId) {
  return db.collection('mini_comments')
    .where({
      postId: postId,
      flag: 0
    })
    .orderBy('timestamp', 'desc')
    .skip((page - 1) * 10)
    .limit(10)
    .get()
}

/**
 * 获取收藏、点赞列表
 * @param {} page 
 */
function getPostRelated(where, page) {
  return db.collection('mini_posts_related')
    .where(where)
    .orderBy('createTime', 'desc')
    .skip((page - 1) * 10)
    .limit(10)
    .get()
}
/**
 * 获取文章详情
 * @param {} id 
 */
function getPostDetail(id) {
  return wx.cloud.callFunction({
    name: 'postsService',
    data: {
      action: "getPostsDetail",
      id: id
    }
  })
}

/**
 * 新增用户收藏文章
 */
function addPostCollection(data) {
  return wx.cloud.callFunction({
    name: 'postsService',
    data: {
      action: "addPostCollection",
      postId: data.postId,
      postTitle: data.postTitle,
      postUrl: data.postUrl,
      postDigest: data.postDigest,
      type: data.type
    }
  })
}

/**
 * 取消喜欢或收藏
 */
function deletePostCollectionOrZan(postId, type) {
  return wx.cloud.callFunction({
    name: 'postsService',
    data: {
      action: "deletePostCollectionOrZan",
      postId: postId,
      type: type
    }
  })
}

/**
 * 新增评论
 */
function addPostComment(commentContent) {
  return wx.cloud.callFunction({
    name: 'postsService',
    data: {
      action: "addPostComment",
      commentContent: commentContent
    }
  })
}

/**
 * 新增用户点赞
 * @param {} data 
 */
function addPostZan(data) {
  return wx.cloud.callFunction({
    name: 'postsService',
    data: {
      action: "addPostZan",
      postId: data.postId,
      postTitle: data.postTitle,
      postUrl: data.postUrl,
      postDigest: data.postDigest,
      type: data.type
    }
  })
}

/**
 * 新增子评论
 * @param {} id 
 * @param {*} comments 
 */
function addPostChildComment(id, postId, comments) {
  return wx.cloud.callFunction({
    name: 'postsService',
    data: {
      action: "addPostChildComment",
      id: id,
      comments: comments,
      postId: postId
    }
  })
}

/**
 * 新增文章二维码并返回临时url
 * @param {*} id 
 * @param {*} postId 
 * @param {*} comments 
 */
function addPostQrCode(postId, timestamp) {
  return wx.cloud.callFunction({
    name: 'postsService',
    data: {
      action: "addPostQrCode",
      timestamp: timestamp,
      postId: postId
    }
  })
}
/**
 * 获取打赏码
 */
function getQrCode() {
  return wx.cloud.getTempFileURL({
    fileList: [{
      fileID: 'cloud://test-91f3af.54ec-test-91f3af/common/1556347401340.jpg'
    }]
  })
}

/**
 * 获取海报的文章二维码url
 * @param {*} id 
 */
function getReportQrCodeUrl(id) {
  return wx.cloud.getTempFileURL({
    fileList: [{
      fileID: id,
      maxAge: 60 * 60, // one hour
    }]
  })
}

function determineAuthor(phoneNumber, callback) {
  let authorId = phoneNumber;
  console.log('determineAuthor by phone ->', authorId)
  db.collection('mini_authors').where({
      _id: authorId
    })
    .field({
      _id: true,
    })
    .get().then(callback)
    .catch(error => {
      console.error(error)
    })
}

async function getAuthorByOpenId(openId) {
  let result = await wx.cloud.callFunction({
    name: 'adminService',
    data: {
      action: "getAuthorByOpenId"
    }
  })
  console.log('getAuthorByOpenId -> ', result)
  if (result.result.data.length > 0) {
    return result.result.data[0]
  }
  return null
}

/**
 * 验证是否是管理员
 */
function checkAuthor(callback) {
  return wx.cloud.callFunction({
    name: 'adminService',
    data: {
      action: "checkAuthor"
    }
  })
}

function updateAuthorOpenIdAndAvatar(id, avatar) {
  console.log('updateAuthorOpenIdAndAvatar ->', id, avatar)
  wx.cloud.callFunction({
    name: 'userService',
    data: {
      action: 'updateAuthorOpenId',
      authorId: id,
      avatar: avatar
    }
  })
}

function saveUser(user) {
  try {
    db.collection('mini_users').where({
      _id: user._id
    }).get().then(res => {
      let result = {}
      if (res.data.length > 0) {
        result = wx.cloud.callFunction({
          name: 'userService',
          data: {
            action: 'updateUser',
            user: user
          }
        })
      } else {
        result = wx.cloud.callFunction({
          name: 'userService',
          data: {
            action: 'saveUser',
            user: user
          }
        })
      }
      console.info('saveUser ->', result)
    })
  } catch (e) {
    console.error('saveUser', e)
    return false
  }
  return true
}

/**
 * 发送评论通知
 * @param {} nickName 
 * @param {*} comment 
 * @param {*} blogId 
 */
function sendTemplateMessage(nickName, comment, blogId, remark, toOpenId) {
  return wx.cloud.callFunction({
    name: 'messageService',
    data: {
      action: "sendTemplateMessage",
      nickName: nickName,
      message: comment,
      blogId: blogId,
      remark: remark,
      toOpenId: toOpenId,
    }
  })
}

/**
 * 新增版本日志
 * @param {} log 
 */
function addReleaseLog(log, title) {
  return wx.cloud.callFunction({
    name: 'adminService',
    data: {
      action: "addReleaseLog",
      log: log,
      title: title
    }
  })
}

/**
 * 更新文章状态
 * @param {*} id 
 * @param {*} isShow 
 */
function updatePostsShowStatus(id, isShow) {
  return wx.cloud.callFunction({
    name: 'adminService',
    data: {
      action: "updatePostsShowStatus",
      id: id,
      isShow: isShow
    }
  })
}

/**
 * 更新文章专题
 * @param {*} id 
 * @param {*} isShow 
 */
function updatePostsClassify(id, classify) {
  return wx.cloud.callFunction({
    name: 'adminService',
    data: {
      action: "updatePostsClassify",
      id: id,
      classify: classify
    }
  })
}

/**
 * 更新文章标签
 * @param {*} id 
 * @param {*} isShow 
 */
function updatePostsLabel(id, label) {
  return wx.cloud.callFunction({
    name: 'adminService',
    data: {
      action: "updatePostsLabel",
      id: id,
      label: label
    }
  })
}

async function deleteGradeById(id) {
  console.info('deleteGradeById -> ', id)
  let res = await wx.cloud.callFunction({
    name: 'adminService',
    data: {
      action: 'deleteGradeById',
      id: id
    }
  })
  console.info('deleteGradeById -> ', res)
  return true
}

async function upsertGrade(grade) {
   let res = await wx.cloud.callFunction({
     name: 'adminService',
     data: {
       action: 'upsertGrade',
       grade: grade
     }
   })
  console.info('upsertGrade -> ', res)
  return true
}

/**
 * 插入管理员
 */
function upsertAuthor(author) {
  try {
    let collection = "mini_authors"
    let id = author._id;
    db.collection(collection)
      .where({
        _id: id
      }).get()
      .then(res => {
        console.log('query author result => ', res)
        let data = res.data
        let result = {}
        if (data.length > 0) {
          delete author.createTime;
          result = wx.cloud.callFunction({
            name: 'adminService',
            data: {
              action: "updateAuthor",
              author: author
            }
          })
        } else {
          result = wx.cloud.callFunction({
            name: 'adminService',
            data: {
              action: "addAuthor",
              author: author
            }
          })
        }
        console.log('upsert author result => ', result)
      })
    return true
  } catch (e) {
    console.error(e)
    return false
  }
}

/**
 * 更新文章标签
 * @param {*} id 
 * @param {*} isShow 
 */
function upsertPosts(id, data) {
  return wx.cloud.callFunction({
    name: 'adminService',
    data: {
      action: "upsertPosts",
      id: id,
      post: data
    }
  })
}

/**
 * 新增基础标签
 */
function addBaseLabel(labelName) {
  return wx.cloud.callFunction({
    name: 'adminService',
    data: {
      action: "addBaseLabel",
      labelName: labelName
    }
  })
}

/**
 * 新增基础主题
 */
function addBaseClassify(classifyName, classifyDesc) {
  return wx.cloud.callFunction({
    name: 'adminService',
    data: {
      action: "addBaseClassify",
      classifyName: classifyName,
      classifyDesc: classifyDesc
    }
  })
}

/**
 * 新增基础主题
 */
function deleteConfigById(id) {
  return wx.cloud.callFunction({
    name: 'adminService',
    data: {
      action: "deleteConfigById",
      id: id
    }
  })
}

function deletePostById(id) {
  return wx.cloud.callFunction({
    name: 'adminService',
    data: {
      action: "deletePostById",
      id: id
    }
  })
}

function deleteAuthorById(id) {
  return wx.cloud.callFunction({
    name: 'adminService',
    data: {
      action: "deleteAuthorById",
      id: id
    }
  })
}

/**
 * 更新评论状态
 * @param {*} id 
 * @param {*} flag 
 */
function changeCommentFlagById(id, flag, postId, count) {
  return wx.cloud.callFunction({
    name: 'adminService',
    data: {
      action: "changeCommentFlagById",
      id: id,
      flag: flag,
      postId: postId,
      count: count
    }
  })
}

/**
 * 获取label集合
 */
function getLabelList() {
  return wx.cloud.callFunction({
    name: 'adminService',
    data: {
      action: "getLabelList"
    }
  })
}

/**
 * 获取label集合
 */
function getClassifyList() {
  return wx.cloud.callFunction({
    name: 'adminService',
    data: {
      action: "getClassifyList"
    }
  })
}

/**
 * 获取label集合
 */
function updateBatchPostsClassify(classify, operate, posts) {
  return wx.cloud.callFunction({
    name: 'adminService',
    data: {
      action: "updateBatchPostsClassify",
      posts: posts,
      operate: operate,
      classify: classify
    }
  })
}

/**
 * 获取label集合
 */
function updateBatchPostsLabel(label, operate, posts) {
  return wx.cloud.callFunction({
    name: 'adminService',
    data: {
      action: "updateBatchPostsLabel",
      posts: posts,
      operate: operate,
      label: label
    }
  })
}

/**
 * 上传文件
 */
function uploadFile(cloudPath, filePath) {
  return wx.cloud.uploadFile({
    cloudPath: cloudPath,
    filePath: filePath, // 文件路径
  })
}

/**
 * 上传文件
 */
async function downloadFile(cloudPath) {
  var result = await wx.cloud.downloadFile({fileID: cloudPath})
  console.log('download ->', result)
  return {
    code: result.statusCode,
    path: result.tempFilePath
  }
}

/**
 * 获取打赏码
 */
function getTempUrl(fileID) {
  return wx.cloud.getTempFileURL({
    fileList: [{
      fileID: fileID
    }]
  })
}

function convertCloud2Http(cloudPath) {
  cloudPath = cloudPath + ''
  var index = cloudPath.indexOf('/', 9);
  var affix = cloudPath.substr(index);
  console.log('url -> ', cloudPath, ' affix ->', affix)
  return config.urlPrefix + affix;
}

module.exports = {
  getPostsList: getPostsList,
  getPostDetail: getPostDetail,
  getPostRelated: getPostRelated,
  getQrCode: getQrCode,
  addPostCollection: addPostCollection,
  addPostZan: addPostZan,
  deletePostCollectionOrZan: deletePostCollectionOrZan,
  addPostComment: addPostComment,
  getPostComments: getPostComments,
  addPostChildComment: addPostChildComment,
  getReportQrCodeUrl: getReportQrCodeUrl,
  addPostQrCode: addPostQrCode,
  checkAuthor: checkAuthor,


  sendTemplateMessage: sendTemplateMessage,
  addReleaseLog: addReleaseLog,
  getReleaseLogsList: getReleaseLogsList,
  getNoticeLogsList: getNoticeLogsList,
  getPostsById: getPostsById,
  deleteConfigById: deleteConfigById,
  addBaseClassify: addBaseClassify,
  addBaseLabel: addBaseLabel,
  upsertPosts: upsertPosts,
  updatePostsLabel: updatePostsLabel,
  updatePostsClassify: updatePostsClassify,
  updatePostsShowStatus: updatePostsShowStatus,
  getCommentsList: getCommentsList,
  changeCommentFlagById: changeCommentFlagById,
  getLabelList: getLabelList,
  getClassifyList: getClassifyList,
  getNewPostsList: getNewPostsList,
  deletePostById: deletePostById,
  uploadFile: uploadFile,
  getTempUrl: getTempUrl,
  updateBatchPostsLabel: updateBatchPostsLabel,
  updateBatchPostsClassify: updateBatchPostsClassify,

  convertCloud2Http: convertCloud2Http,

  upsertAuthor: upsertAuthor,
  getAuthorsList: getAuthorsList,
  deleteAuthorById: deleteAuthorById,
  getAuthorById: getAuthorById,
  getAuthorByOpenId: getAuthorByOpenId,
  saveUser: saveUser,
  updateAuthorOpenIdAndAvatar: updateAuthorOpenIdAndAvatar,
  determineAuthor: determineAuthor,
  getGradeList: getGradeList,
  getGradeById: getGradeById,
  upsertGrade: upsertGrade,
  deleteGradeById: deleteGradeById,
  deleteDocById: deleteDocById,
  getDocById: getDocById,
  getMajorList: getMajorList,
  saveAdminDoc: saveAdminDoc,
  getCollegeList: getCollegeList,

  downloadFile: downloadFile,
  addPostDownload: addPostDownload,
  addPostView: addPostView,
}